import dayjs from 'dayjs';

const categoryTabMap = {
    'all': '全部',
    'document': '文档',
    'audio': '音频',
    'video': '视频',
    'img': '图片',
    'other': '其它'
  };
  const mimetypeRegMap = {
    'doc': /^application\/(msword|vnd.openxmlformats-officedocument.wordprocessingml.document)$/i,
    'xls': /^application\/(vnd.ms-excel|vnd.openxmlformats-officedocument.spreadsheetml.sheet)$/i,
    'ppt': /^application\/(vnd.ms-powerpoint|vnd.openxmlformats-officedocument.presentationml.presentation)$/i,
    'pdf': /^application\/pdf$/i,
    'audio': /^audio\//i,
    'video': /^video\//i,
    'image': /^image\//i
  };
  const typeInCategory = {
    'all': [],
    'document': ['doc', 'docx', 'ppt', 'pptx', 'txt', 'xls', 'xlsx', 'pdf', 'rtf', 'odt'],
    'audio': ['mp3', 'wma', 'flac', 'm4a', 'ogg', 'ape', 'amr', 'wav', 'aac', 'aiff', 'caf'],
    'video': ['mkv', 'rmvb', 'rm', 'wmv', 'avi', 'mp4', 'mov', 'mpg', 'asf', 'mpeg', 'vob', '3gp', 'flv', 'ts', 'mts', 'f4v', 'dv', 'm4v', 'mjpeg', 'swf', 'webm'],
    'img': ['bmp', 'jpg', 'tiff', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'png'],
    'other': ['rar', 'zip']
  };
  
  /**
   * @param types ['all', 'document', 'audio', 'video', 'img', 'other']
   * @returns {array}
   *  [
   *    { key: 'all', value: '全部' },
   *    { key: 'document', value: '文档' },
   *    { key: 'video', value: '视频' },
   *    ...
   *  ]
   */
  export function getMaterialTypeTabs(types = []) {
    if (types.length === 0) {
      types = ['all', 'document', 'audio', 'video', 'img', 'other']
    }
  
    return types.map(type => typeof type === 'object' ? type : {
      key: type,
      value: categoryTabMap[type]
    })
  }
  
  /**
   * @param extensions ['doc', 'mp3', 'png', 'avi', 'zip']
   * @returns {string} '.doc,.mp3,.png,.avi,.zip'
   */
  export function getFileAcceptType(extensions) {
    return extensions.map(ex => `.${ex}`).join(',');
  }
  
  /**
   * 将文件大小格式化处理
   *
   * @param size 1024000000
   * @returns {string} '976.56MB'
   */
  export function formatFileSize(size) {
    let fsText;
  
    if (size < 1048576) fsText = (size / 1024).toFixed(2) + 'KB';
    else if (size === 1048576) fsText = '1MB'
    else if (size > 1048576 && size < 1073741824) fsText = (size / (1024 * 1024)).toFixed(2) + 'MB';
    else if (size > 1048576 && size === 1073741824) fsText = '1GB';
    else if (size > 1073741824 && size < 1099511627776) fsText = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
    else fsText = '1TB+'
  
    return fsText;
  }
  /**
   * 将社区时间格式化处理
   *
   * @param time 任意时间戳 1636600271000
   * @returns {string} '2021年11月11日' | '11月11日' | '昨天' | '2小时前' | '30分钟前' | '刚刚'
   */
  export function formatTime(time) {
    let date = new Date(time);
    let y = date.getFullYear(),
        m = date.getMonth() + 1,
        d = date.getDate();
  
    let nowDate = new Date();
    let nowY = nowDate.getFullYear();
    let nowTime = nowDate.getTime();
  
    let diff = nowTime - time;
    let dd = Math.floor(diff / (1000 * 60 * 60 * 24));
    let dh = Math.floor(diff / (1000 * 60 * 60));
    let dm = Math.floor(diff / (1000 * 60));
  
    if (nowY > y) return y + '年' + m + '月' + d + '日';
    else if (Math.floor(dd) > 1) return m + '月' + d + '日';
    else if (dd === 1) return '昨天';
    else if (dh >= 1) return '' + dh + '小时前';
    else if (dm >= 5) return '' + dm + '分钟前';
    else return '刚刚';
  }
  /**
   * 将文件类型格式化处理
   *
   * @param mimetype 'application/msword' | 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
   * @returns {string} 'doc'
   */
  export function formatFileTypeClasses(mimetype) {
    return Object.keys(mimetypeRegMap).find(key => mimetypeRegMap[key].test(mimetype)) || '';
  }
  
  /**
   * 获取文件的扩展名
   *
   * @param fileName '/path/to/filename.mp3'
   * @returns {string} 'mp3'
   */
  export function getFileExtension(fileName) {
    return fileName.replace(/.+\./, '').toLowerCase();
  }
  /**
   * 获取文件所属类别
   *
   * @param fileName '/path/to/filename.mp4'
   * @returns {string} 'video'
   */
  export function getFileCategory(fileName) {
    return Object.keys(typeInCategory).find(key => typeInCategory[key].includes(getFileExtension(fileName)));
  }
  
  /**
   * 通过类别获取允许上传的文件类型
   *
   * @param category 'document'
   * @returns {string} '.doc,.docx,.ppt,.pptx,.txt,.xls,.xlsx,.pdf,.rtf,.odt'
   */
  export function getAcceptByCategory(category) {
    if (category) {
      return typeInCategory[category].map(ext => '.' + ext).join(',');
    }
  
    return '';
  }
  
  /**
   * 通过文件后缀名检出上传类型不符合的文件
   *
   * @param accept '.mp3,.ogg,.wav,.aac,.doc,.ppt,.avi,.zip'
   * @param filesExtension ['doc', 'ppt']
   */
  export function inspectFileType(accept, filesExtension) {
    if (accept && accept.length) {
      const acceptArr = accept.split(','); // ['.mp3', '.ogg', '.wav', '.aac']
      const unmatchedTypes = filesExtension.filter(ext => !(acceptArr.includes('.' + ext)));
  
      if (unmatchedTypes.length) {
        return new Set(unmatchedTypes);
      }
    }
  
    return false;
  }


/* 通过文件后缀名检出上传类型不符合的文件 */
export function filesTypeInspect(strainer, files) {
    if (strainer && strainer.length) {
      strainer = strainer.split(',');
      let fileNames = Array.prototype.map.call(files, file => `.${getFileExtension(file.name)}`);
      let notMatchTypes = fileNames.filter(name => !(strainer.includes(name)));
  
      if (notMatchTypes.length) {
        return new Set(notMatchTypes);
      }
    }
  
    return false;
  }

  /**
  * 将社区时间格式化处理
  *
  * @param time 任意时间戳 1318781876406
  * @param emptyText 时间为空时返回的字段 -
  * @param formatType 时间格式 YYYY.MM.DD HH:mm
  * @returns {string} '2011-10-17 00:17'
  */
  export function formatDateByType(time, emptyText = '-', formatType = 'YYYY.MM.DD HH:mm') {
    if (!time) {
      return emptyText;
    }
    return dayjs(time).format(formatType);
  }